<template>
  <div class="px-35 rounded-10 bg-white">
    <div text-28 font-medium pt-40 text-center>用户登录</div>
    <div text-12 leading-36 font-medium text-center>USERLOGIN</div>

    <!-- 登录表单 -->
    <el-form
      ref="loginFormRef"
      mt-10
      :model="loginForm"
      :rules="formRule"
      label-width="auto"
      size="large"
    >
      <!-- 用户名/手机号 -->
      <el-form-item prop="loginName">
        <el-input v-model="loginForm.loginName" placeholder="用户名/手机号" clearable />
      </el-form-item>

      <!-- 密码 -->
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          placeholder="密码长度6～16位"
          clearable
          maxlength="16"
          show-password
        />
      </el-form-item>

      <!-- 图形验证码 -->
      <el-form-item v-if="isShowImgCode" prop="verifyCode" flex-between>
        <el-input
          v-model="loginForm.verifyCode"
          placeholder="请输入图形验证码"
          class="mr-10 flex-1"
        >
          <!-- <template #prepend>
            <i-ep-arrow-right-bold class="text-20 color-primary" />
          </template> -->
        </el-input>
        <div flex-y-center w-80>
          <el-image
            v-show="!imgCodeState.loading"
            :src="imgCodeState.path"
            alt="图形验证码"
            title="换一张"
            style="width: 100%; height: 40px"
            @click="onLoadImgPath"
          />
        </div>
      </el-form-item>

      <!-- 登录 -->
      <el-form-item class="mt-30">
        <el-button
          :disabled="loginLoading"
          :loading="loginLoading"
          type="primary"
          class="text-16 w-full"
          @click="onLogin(loginFormRef)"
        >
          登录
        </el-button>
      </el-form-item>

      <!-- 记住账号 -->
      <el-form-item mt--20>
        <el-checkbox v-model="isRememberAccount">记住账号</el-checkbox>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import type { LoginReq } from '@/api/type'
import { userApi } from '@/api'
import router from '@/router'
import { getTopMenu, initRouter } from '@/router/utils'
import { useUserStore } from '@/store/user'
import { message } from '@/utils/message'
import { formRule } from '../config/form-rules'
import { useLoginStore } from '../store/login'

const loginStore = useLoginStore()
const { errorTimes, isShowImgCode, isRememberAccount, loginName, password } =
  storeToRefs(loginStore)

// ---------------------- 表单 ----------------------
const loginForm = ref<Partial<LoginReq>>({
  loginName: loginName.value,
  password: password.value,
})

// ---------------------- 图形验证码 ----------------------
const imgCodeState = ref({
  loading: false,
  path: '',
})

const onLoadImgPath = () => {
  if (imgCodeState.value.loading) return
  imgCodeState.value.loading = true
  userApi
    .getImgCode()
    .then(({ model }) => {
      imgCodeState.value.path = `data:image/png;base64,${model[0]}`
    })
    .finally(() => (imgCodeState.value.loading = false))
}

// ---------------------- 登录 ----------------------
const loginFormRef = ref<FormInstance>()
const loginLoading = ref(false)
const userStore = useUserStore()
const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(valid => {
    if (valid) {
      loginLoading.value = true
      userStore
        .doLogin(loginForm.value)
        .then(() => {
          // 记住账号
          if (isRememberAccount.value) {
            loginName.value = loginForm.value.loginName ?? ''
            password.value = loginForm.value.password ?? ''
          } else {
            loginName.value = ''
            password.value = ''
          }

          // 获取后端路由
          initRouter().then(() => {
            router.push(getTopMenu(true).path ?? '/').then(() => {
              message('登录成功', { type: 'success' })
              errorTimes.value = 0
            })
          })
        })
        .catch(() => {
          errorTimes.value++
          errorTimes.value >= 3 && onLoadImgPath()
        })
        .finally(() => (loginLoading.value = false))
    }
  })
}
</script>
